<template>
<div>
    <el-card>
    <el-row :gutter="20">
  <el-col :span="8">
     <el-input placeholder="请输入内容" v-model="userinfo.query" @clear="getin" @input='getin'>
     <el-button slot="append" icon="el-icon-search" @click="getin"></el-button>
     </el-input>
  </el-col>
  <el-col :span="2">
     <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
  </el-col>
</el-row>
<!-- 表格区-->
<el-table :data="userlist" style="width: 100%" stripe border>
      <el-table-column type="index" label="#" ></el-table-column>
      <el-table-column prop="username" label="姓名" ></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色" ></el-table-column>
      <el-table-column prop="mg_state" label="状态" >
      <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change='userStus(scope.row)'></el-switch>
      </template>
      </el-table-column>
      <el-table-column prop="type" label="操作" width="180px">
      <template slot-scope="scope">
       <!--修改用户信息-->
      <el-button type="primary" icon="el-icon-edit" size="mini" @click="xiushowUser(scope.row.id)"></el-button>
      <!-- 删除用户-->
      <el-button type="danger" icon="el-icon-delete" size="mini" @click="reveoUser(scope.row.id)"></el-button>
      <el-tooltip class="item" effect="dark" content="角色" placement="top" :enterable="false">
      <!--操作角色-->
      <el-button type="warning" icon='el-icon-setting' size="mini"></el-button>
      </el-tooltip>
      </template>
      </el-table-column>
    </el-table>
    <!--分页区-->
   <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userinfo.pagenum"
      :page-sizes="[2, 3, 5, 7]"
      :page-size="userinfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--弹出表单区-->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width="30%" @close='addDialg("inputForm")'>
  <el-form :rules="inputRuls" :model="inputList" ref="inputForm" label-width="80px">
    <el-form-item label="用户名：" prop="username">
      <el-input v-model="inputList.username"  ></el-input>
    </el-form-item>
    <el-form-item label="密码：" prop="password">
      <el-input v-model="inputList.password"  ></el-input>
    </el-form-item>
    <el-form-item label="邮箱：" prop="email">
      <el-input v-model="inputList.email" ></el-input>
    </el-form-item>
    <el-form-item label="电话：" prop="mobile">
      <el-input v-model="inputList.mobile" ></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUsers">确 定</el-button>
  </div>
</el-dialog>
<!--修改用户信息-->
<el-dialog title="提示" :visible.sync="putdialogVisible" width="30%"  @close='addDialg("eaitForm")'>
   <el-form :rules="eaitRuls" :model="userObj" ref="eaitForm" label-width="80px">
    <el-form-item label="用户名：" >
      <el-input v-model="userObj.username" :disabled="true" ></el-input>
    </el-form-item>
    <el-form-item label="邮箱：" prop="email">
      <el-input v-model="userObj.email" ></el-input>
    </el-form-item>
    <el-form-item label="电话：" prop="mobile">
      <el-input v-model="userObj.mobile" ></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="putdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="putUser">确 定</el-button>
  </span>
</el-dialog>
</el-card>
    </div>
</template>
<script>
export default {
  data () {
    // 邮箱验证
    var chickEmail = (rule, value, cb) => {
      let regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('邮箱错误!'))
    }
    // 手机号码验证
    var chickMobile = (rule, value, cb) => {
      let regEmail = /^1(3|4|5|7|8)\d{9}$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('手机号错误!'))
    }
    return {
      userinfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      dialogFormVisible: false,
      inputList: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      inputRuls: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登陆密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: chickEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: chickMobile, trigger: 'blur' }
        ]
      },
      putdialogVisible: false,
      // 修改用户对象
      userObj: {},
      eaitRuls: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: chickEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: chickMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getin()
  },
  methods: {
    async getin () {
      var { data: res } = await this.axios.get('users', { params: this.userinfo })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log('====' + this.total)
    },
    handleSizeChange (val) {
      this.userinfo.pagesize = val
      this.getin()
    },
    handleCurrentChange (val) {
      this.userinfo.pagenum = val
      this.getin()
    },
    async userStus (val) {
      let { data: res } = await this.axios.put(`users/${val.id}/state/${val.mg_state}`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('修改失败')
      }
    },

    addUsers () {
      this.$refs.inputForm.validate(async valid => {
        //  能进来说明输入的都合法了
        // 那就发送请求给后台了
        if (!valid) return
        let { data: res } = await this.axios.post('users', this.inputList)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.error('添加成功')
        this.dialogFormVisible = false
        this.getin()
      })
    },
    addDialg (id) {
      this.$refs[id].resetFields()
      // console.log('sadsdkfasdf')
    },
    async xiushowUser (id) {
      this.putdialogVisible = true
      let { data: res } = await this.axios.get(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.userObj = res.data
      // console.log(this.userObj)
    },
    // 修改用户方法
    putUser () {
      this.$refs.eaitForm.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.axios.put(`users/${this.userObj.id}`, { email: this.userObj.email, mobile: this.userObj.mobile })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改用户失败')
        this.putdialogVisible = false
        this.getin()
        this.$message.success('修改成功')
      })
    },
    // 删除用户
    async  reveoUser (id) {
      let res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') {
        return this.$message.info('取消删除')
      }

      let { data: ros } = await this.axios.delete(`users/${id}`)
      // console.log(ros)
      if (ros.meta.status !== 200) return this.$message.error('删除失败')
      this.getin()
      this.$message.success('删除成功')
    }
  }
}
</script>
<style lang="less" scoped>
    .el-card{
       box-shadow:0 0 5px #cfcfcf !important;
    }
    .el-table{
      margin-top: 20px;
    }
    .el-pagination{
      margin-top: 15px;
    }
</style>
